package org.ssssssss.magicapi.scomm;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.util.StringUtils;
import org.ssssssss.magicapi.core.service.MagicAPIService;

import purejavacomm.CommPortIdentifier;
import purejavacomm.SerialPort;
import purejavacomm.SerialPortEvent;
import purejavacomm.SerialPortEventListener;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author：zcg
 * @name：CommUtil
 * @Date：2023/12/13
 * @describe：
 */

public class CommUtil implements SerialPortEventListener {
	private static final Logger log = LoggerFactory.getLogger(CommUtil.class);
	
    private String PORT_NAME ;
    private static final int BIT_RATE = 9600;
    public static final int DATA_BITS = SerialPort.DATABITS_8;
    public static final int STOP_BIT = SerialPort.STOPBITS_1;
    public static final int PARITY_BIT = SerialPort.PARITY_NONE;

    public static SerialPort serialPort;
    private static InputStream in;
    private static OutputStream out;
    private static CommUtil commUtil;

    // 保存串口返回信息
    public String dataStr;
    // 保存串口返回的字节数组
    public byte[] dataB;
    // 保存串口返回信息十六进制
    public String dataHex;

    public static final int MSG_ASCII = 1;
    public static final int MSG_BYTE = 2;
    public static final int MSG_HEX = 3;
    private MagicAPIService service;
    private String monitorApi;// 监听接收数据的回调api
    private int msgType = MSG_ASCII; // 
    
    private CommUtil(String PORT_NAME) {
        this.PORT_NAME = PORT_NAME;
    }

    public static synchronized CommUtil getInstance(String PORT_NAME) {
        if (commUtil == null) {
            commUtil = new CommUtil(PORT_NAME);
            commUtil.init();
        }else if(!commUtil.PORT_NAME.equals(PORT_NAME))
        {
            commUtil = new CommUtil(PORT_NAME);
            commUtil.init();
        }
        return commUtil;
    }

    public void init( ) {
        try {
            if(StringUtils.isEmpty(PORT_NAME)){
                log.error("初始化，串口名为 空");
            }
            else {
	            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(PORT_NAME);
	            if (portIdentifier.isCurrentlyOwned()) {
	                log.error("Port is currently in use");
	            } else if (portIdentifier.getPortType() == 1) {
	                serialPort = (SerialPort) portIdentifier.open(PORT_NAME, 1000);
	                serialPort.setSerialPortParams(BIT_RATE, DATA_BITS, STOP_BIT, PARITY_BIT);
	
	                in = serialPort.getInputStream();
	                out = serialPort.getOutputStream();
	
	                serialPort.addEventListener(this);
	                serialPort.notifyOnDataAvailable(true);
	            } else {
	                log.error("Error: Only serial ports are handled by this example.");
	            }
            }
        } catch (Exception e) {
        	commUtil = null;
            log.error("串口初始化失败:",e);
        }
    }

    @Override
    public void serialEvent(SerialPortEvent serialPortEvent) {
        switch (serialPortEvent.getEventType()) {
            case SerialPortEvent.DATA_AVAILABLE:
                if(receive()>0&&monitorApi.length()>0)
                	sendMsg();
                break;
        }
    }
    public void setApi(MagicAPIService service, String monitorApi,int type) {
		this.service = service;
		this.monitorApi = monitorApi;
		this.msgType = type;
    }
    public void sendMsg() {
		String method = "GET";
        Map<String, Object> params = new HashMap<>();	
        params.put("name",PORT_NAME);	
        if(msgType==MSG_ASCII) params.put("data",dataStr);
        else if(msgType==MSG_BYTE) params.put("data",dataB);
        else if(msgType==MSG_HEX) params.put("data",dataHex);		
        service.execute(method, monitorApi, params);
    }
    public void send(String message) {
        try {
            //log.info("sendmsg:{}",message);
            byte[] bytes = hexStrToByteArray(message);
            out.write(bytes);
//            Thread.sleep(1000);
        } catch (Exception e) {
            log.error("串口发送失败:",e);
        }
    }

    public int receive() {
        int len = 0;
        try {
            in = serialPort.getInputStream();
            // 通过输入流对象的available方法获取数组字节长度
            byte[] readBuffer = new byte[in.available()];
            // 从线路上读取数据流
            while ((len = in.read(readBuffer)) != -1) {
                // 直接获取到的数据
            	dataB = readBuffer;
                dataStr = new String(readBuffer, 0, len).trim();
                // 转为十六进制数据
                dataHex = bytesToHexString(readBuffer);
                in.close();
                in = null;
                if(len>0) System.out.println(("读取："+len+"--"+dataHex));
                break;
            }
        } catch (IOException e) {
            System.out.println(("读取串口数据时发生IO异常"));
        }
        return len;
    }


    public void close() {
        try {
            in.close();
            out.close();
            serialPort.notifyOnDataAvailable(false);
            serialPort.removeEventListener();
            serialPort.close();
        } catch (Exception e) {
            log.error("close",e);
        }
    }



    //16进制转byte数组
    public static byte[] hexStrToByteArray(String str) {
        if (str == null) {
            return null;
        }
        if (str.length() == 0) {
            return new byte[0];
        }
        byte[] byteArray = new byte[str.length() / 2];
        for (int i = 0; i < byteArray.length; i++) {
            String subStr = str.substring(2 * i, 2 * i + 2);
            byteArray[i] = ((byte) Integer.parseInt(subStr, 16));
        }
        return byteArray;
    }

    public static String ByteArrayToString(byte[] by) {
        String str = "";
        for (int i = 0; i < by.length; i++) {
            String hex = Integer.toHexString(by[i] & 0xFF);
            if (hex.length() == 1) {
                hex = "0" + hex;
            }
            str += hex.toUpperCase();
        }
        return str;
    }

    /**
     * 数组转换成十六进制字符串
     * @param
     * @return HexString
     */
    public static final String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 获取源数据和验证码的组合byte数组
     * @param aa 字节数组
     * @return
     */
    public static byte[] getData(byte[] aa) {
//        byte[] bb = getCrc16(aa);
        byte[] cc = new byte[aa.length];
        System.arraycopy(aa,0,cc,0,aa.length);
        return cc;
    }

    public static byte[] getData(String...strings) {
        byte[] data = new byte[]{};
        for (int i = 0; i<strings.length;i++) {
            int x = Integer.parseInt(strings[i], 16);
            byte n = (byte)x;
            byte[] buffer = new byte[data.length+1];
            byte[] aa = {n};
            System.arraycopy( data,0,buffer,0,data.length);
            System.arraycopy( aa,0,buffer,data.length,aa.length);
            data = buffer;
        }
        return getData(data);
    }

    public static String byteTo16String(byte b) {
        StringBuffer buffer = new StringBuffer();
        int aa = (int)b;
        if (aa<0) {
            buffer.append(Integer.toString(aa+256, 16)+" ");
        }else if (aa==0) {
            buffer.append("00 ");
        }else if (aa>0 && aa<=15) {
            buffer.append("0"+Integer.toString(aa, 16)+" ");
        }else if (aa>15) {
            buffer.append(Integer.toString(aa, 16)+" ");
        }
        return buffer.toString();
    }
}
